﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using UnityScriptEngine;

namespace EnrollmentSystem
{
    public partial class frmGradesManagement : Form
    {
        UnityProcessor proc = new UnityProcessor();
        Threader t = new Threader();
        
        UnityScript[] uSchedTbl = new UnityScript[0];
        UnityElement eSched;
        UnityScript[] uGradeTbl = new UnityScript[0];
        UnityElement eGrade;

        //Data Attributes
        string prevSrc = "", EnNo = "";
        int selSched = -1, selGrade = -1;
        public frmGradesManagement()
        {
            InitializeComponent();
            InitializeFrameSliderForm();
        }
        private void InitializeForm()
        {
            DoEvents();
            UnityEvents();
            LoadEnrollment();
        }
        void DoEvents()
        {
            txtSearch.KeyPress += new KeyPressEventHandler(delegate(object sender, KeyPressEventArgs e)
            {
                if (e.KeyChar == (char)13)
                {
                    txtPage.Value = 1m;
                    prevSrc = txtSearch.Text;
                    LoadEnrollment();
                }
            });
            txtPage.ValueChanged += new EventHandler(delegate
            {
                LoadEnrollment();
            });
            grdEnrollment.DoubleClick += new EventHandler(delegate
            {
                if (grdEnrollment.SelectedRows.Count > 0)
                {
                    
                    selSched = grdEnrollment.SelectedRows[0].Index;
                    uSchedTbl[0].Data_Get(selSched, out eSched);
                    EnNo = eSched.Data_GetField(0).ToString();

                    LoadGrades();
                }
            });
            btnCloseGrade.Click += new EventHandler(delegate
            {
                GradePanel(false);
            });
            grdGrades.SelectionChanged += new EventHandler(delegate
            {
                if (grdGrades.SelectedRows.Count > 0)
                {
                    selGrade = grdGrades.SelectedRows[0].Index;
                    uGradeTbl[0].Data_Get(selGrade, out eGrade);
                    txtGrade.Value = decimal.Parse(eGrade.Data_GetField(1).ToString());
                    txtRemarks.Text = eGrade.Data_GetField(3).ToString();
                }
            });
            btnCommit.Click += new EventHandler(delegate
            {
                SaveGrades();
            });
        }
        void UnityEvents()
        {
            proc.ProcessCompleted += new ProcessHandler(delegate(string id, string desc)
            {
                t.SafeCall(this, delegate
                {
                    switch (id)
                    {
                        case "LOADENROLLMENT":
                            proc.DBPUX_Data_Fetch(out uSchedTbl);
                            grdEnrollment.DataSource = uSchedTbl[0].ToDataTable();
                            if (uSchedTbl[0].Data_Count == 50)
                                txtPage.Maximum = txtPage.Value + 1;
                            else
                                txtPage.Maximum = txtPage.Value;
                            MainPanel(true);
                            FormatGrid();
                            break;
                        case "LOADGRADES":
                            proc.DBPUX_Data_Fetch(out uGradeTbl);

                            txtRemarks.Items.Clear();
                            txtRemarks.Items.AddRange(uGradeTbl[1].ToList(0));

                            txtEnrollmentNum.Text = eSched.Data_GetField(0).ToString();
                            txtName.Text = eSched.Data_GetField(1).ToString();
                            txtCourse.Text = eSched.Data_GetField(2).ToString();
                            txtSemester.Text = eSched.Data_GetField(3).ToString();
                            txtCategory.Text = eSched.Data_GetField(4).ToString();
                            txtYearLevel.Text = eSched.Data_GetField(5).ToString();

                            grdGrades.DataSource = uGradeTbl[0].ToDataTable();

                            FormatGrid();
                            GradePanel(true);
                            break;
                        case "SAVEGRADES":
                            LoadGrades();
                            break;
                    }
                });
            });
            proc.ProcessError += new ProcessHandler(delegate(string id, string desc)
            {
                t.SafeCall(this, delegate
                {
                    MessageBox.Show(desc, "UnityScript", MessageBoxButtons.OK, MessageBoxIcon.Error);
                });
            });
        }
        
        //Data Operations
        void LoadEnrollment()
        {
            MainPanel(false);
            UnityScript u = new UnityScript("LOADENROLLMENT", 5);
            u.Script_Add(Script.DBPUX_BEGIN);
            u.Script_Add(Script.DBPUX_QUERY, string.Format("SELECT fID, fEnrollmentNumber AS 'Enrollment Number', fName AS 'Student Name', fCourse AS 'Course', fSchoolYear AS 'SEM S.Y.', fStudentCat AS 'Category', fYearLevel as 'YearLevel',  fStamp " +
                 "FROM tblenrollment T1, (SELECT fName, fNumber, fCourse FROM tblstudentprofile) AS T2 WHERE (T2.fNumber = T1.fStudentNumber) AND ((fStudentNumber LIKE '%{0}%') OR (fName LIKE '%{0}%') OR " +
                 "(fEnrollmentNumber LIKE '%{0}%')) ORDER BY fSchoolYear DESC, fEnrollmentNumber ASC " +
                 "LIMIT {1}, 50",
                 prevSrc,
                 (txtPage.Value - 1m) * 50
                 )
                 );
            u.Script_Add(Script.DBPUX_COMMIT);
            proc.Run(u);
        }
        void LoadGrades()
        {
            MainPanel(false);
            UnityScript u = new UnityScript("LOADGRADES", 5);
            u.Script_Add(Script.DBPUX_BEGIN);
            u.Script_Add(Script.DBPUX_QUERY, string.Format("SELECT fID, fCode AS 'Title', fGrade AS 'Grade', fUnits AS 'Units', fRemarks As 'Remarks', fStamp FROM tblgrades T1, " +
                "(SELECT fID as ffID, fCode FROM tblsubjectplanner t2) AS T2 WHERE " +
                "(ffID=fSubjectCode) AND (fEnrollmentNum='{0}') ORDER BY fCode ASC",
                EnNo
                )
                );
            u.Script_Add(Script.DBPUX_QUERY, "SELECT fID, fData, fStamp FROM tbllookup WHERE fKey='GRADE_REMARKS' ORDER BY fData ASC");
            u.Script_Add(Script.DBPUX_COMMIT);
            proc.Run(u);
        }
        void SaveGrades()
        {
            MainPanel(false);
            UnityScript u = new UnityScript("SAVEGRADES", 5);
            u.Script_Add(Script.DBPUX_BEGIN);
            u.Script_Add(Script.DBPUX_UPDATE, string.Format("tblgrades SET fGrade='{0}', fRemarks='{1}'", txtGrade.Value, txtRemarks.Text),
                string.Format("(fID='{0}') AND (fStamp='{1}')",
                eGrade.Data_ID,
                eGrade.Data_Stamp
                ));
            u.Script_Add(Script.DBPUX_COMMIT);
            proc.Run(u);
        }
        //GUI
        void FormatGrid()
        {
            foreach (DataGridViewColumn col in grdEnrollment.Columns)
            {
                col.Width = (grdEnrollment.Width / grdEnrollment.Columns.Count) - 10;
                col.SortMode = DataGridViewColumnSortMode.NotSortable;
            }
            foreach (DataGridViewColumn col in grdGrades.Columns)
            {
                col.Width = (grdGrades.Width / grdGrades.Columns.Count) - 10;
                col.SortMode = DataGridViewColumnSortMode.NotSortable;
            }
        }
        void GradePanel(bool show)
        {
            pnlGrades.Visible = show;
            MainPanel(!show);
            if (!show)
            {
                foreach (Control ctl in pnlGrades.Controls)
                {
                    if (ctl is TextBox) ((TextBox)ctl).Text = "";
                    if (ctl is ComboBox) ((ComboBox)ctl).SelectedIndex = -1;
                    if (ctl is DateTimePicker) ((DateTimePicker)ctl).Value = DateTime.Now;
                    if (ctl is CheckBox) ((CheckBox)ctl).Checked = false;
                    if (ctl is NumericUpDown) ((NumericUpDown)ctl).Value = 0;
                    if (ctl is DataGridView) ((DataGridView)ctl).DataSource = null;
                }
            }
        }
        void MainPanel(bool enable)
        {
            txtSearch.Enabled = enable;
            txtPage.Enabled = enable;
            grdEnrollment.Enabled = enable;
        }
    }
}
